'use strict';
var os = require('os');

// 获取局域网ip
function getLocalIp() {
    var map = [];
    var ifaces = os.networkInterfaces();
    for (var dev in ifaces) {
        if (ifaces[dev][1].address.indexOf('192.168') != -1) {
            return ifaces[dev][1].address;
        }
    }
    return map;
}

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var port = process.env.PORT || 3000;
const ip = getLocalIp()
server.listen(port, function () {
    // 文件上传地址，局域网时 测试app手机和后端服务在同一局域网
    console.log('Server listening at %s:%d', ip, port);
});


var fs = require('fs');
var chunks = [];
app.post('/upload', function (req, res) {
    chunks = [];
    req.on('data', function (chunk) {
        chunks.push(chunk);

    });

    req.on('end', function () {
        var data = Buffer.concat(chunks);
        //保存在项目根目录下，文件名时间戳
        const filePathName = `${Date.now()}.amr`
        fs.writeFile(filePathName, data, 'binary', function (err) {
            if (err)
                console.log('couldnt make file' + err);
            else
                console.log("Audio Recieved:", data);
            res.end();
        });

    });
});


